

#include "mlink.h"
#include "mdf_info_store.h"
#include "mlink_lora_handle.h"
#include "E32_433T33S.h"

static const char *TAG                       = "Mlink Lora";

#define E32_CONFIG_STROE_KEY "e32_config"

int lora_load_config( lora_config_t *config ) {
	// int ret = MDF_OK;
	return mdf_info_load(E32_CONFIG_STROE_KEY, config, sizeof(lora_config_t));
}

int lora_save_config( lora_config_t *config ) {
	// int ret = MDF_OK;
	return mdf_info_save(E32_CONFIG_STROE_KEY, config, sizeof(lora_config_t));
}

static int mlink_handle_set_lora_config(mlink_handle_data_t *handle_data)
{
    int ret   = MDF_OK;
	lora_config_t config=LORA_DEFAULT_CONFIG;
	lora_load_config( &config );
    int val;
    ret = mlink_json_parse(handle_data->req_data, "en", &val);
    MDF_ERROR_CHECK(ret != MDF_OK, ret, "Parse the json formatted string");
    config.en = val;
    ret = mlink_json_parse(handle_data->req_data, "addr", &val);
    MDF_ERROR_CHECK(ret != MDF_OK, ret, "Parse the json formatted string");
    config.addr = val;
    ret = mlink_json_parse(handle_data->req_data, "ch", &val);
    MDF_ERROR_CHECK(ret != MDF_OK, ret, "Parse the json formatted string");
    config.ch = val;
    ret = mlink_json_parse(handle_data->req_data, "sp", &val);
    MDF_ERROR_CHECK(ret != MDF_OK, ret, "Parse the json formatted string");
    config.sp = val;
    ret = mlink_json_parse(handle_data->req_data, "pwr", &val);
    MDF_ERROR_CHECK(ret != MDF_OK, ret, "Parse the json formatted string");
    config.pwr = val;

	lora_save_config(&config);
    return MDF_OK;
}

static int mlink_handle_get_lora_config(mlink_handle_data_t *handle_data)
{
    int ret      = ESP_OK;
	lora_config_t config=LORA_DEFAULT_CONFIG;
	lora_load_config( &config );
	handle_data->resp_size = mlink_json_pack(&handle_data->resp_data, "en", config.en);
    handle_data->resp_size = mlink_json_pack(&handle_data->resp_data, "addr", config.addr);
    handle_data->resp_size = mlink_json_pack(&handle_data->resp_data, "ch", config.ch);
    handle_data->resp_size = mlink_json_pack(&handle_data->resp_data, "sp", config.sp);
    handle_data->resp_size = mlink_json_pack(&handle_data->resp_data, "pwr", config.pwr);
    return ret;
}

int mlink_lora_init(void)
{
    int ret      = ESP_OK;

	ret = mlink_set_handle("set_lora_config", mlink_handle_set_lora_config);
    ret = mlink_set_handle("get_lora_config", mlink_handle_get_lora_config);
	return ret;
}

